
/**
 * 添加遮罩层
 */
//document.write('<div id="vjs-view-loading" class="vjs-view-loading"><span id="vjs-loading-route" class="vjs-loading-route"><i class="iconfont icon-loading"></i></span></div>');

/**
 * 获取js当前目录
 */
var js=document.scripts;
var js_document = "";
for(var i=js.length;i>0;i--){
	if(js[i-1].src.indexOf("vjs.js")>-1){
		js_document=js[i-1].src.substring(0,js[i-1].src.lastIndexOf("/")+1);
	}
	if(js[i-1].src.indexOf("vjs.min.js")>-1){
		js_document=js[i-1].src.substring(0,js[i-1].src.lastIndexOf("/")+1);
	}
}

/**
 * 加载其他的js文件
 */
document.write("<script src='"+js_document+"jquery-1.9.1.min.js'></script>");
document.write("<script src='"+js_document+"bootstrap.min.js'></script>");
document.write("<script src='"+js_document+"jquery.cookie.js'></script>");
document.write("<script src='"+js_document+"jsencrypt.js'></script>");
document.write("<script src='"+js_document+"template.js'></script>");
document.write("<script src='"+js_document+"jquery.base64.js'></script>");

/**
 * vjs核心
 */
var vjs = function(){

	/**
	 * 待处理事件
	 */
	var _func = new Array();

	/**
	 * 加载完成，执行/注册待处理事件
	 */
	var _load = function(){
		var queue = new Array();
		queue = _func.concat();
		_func.length = 0;
		$.each(queue, function(i,o){
			if(o){
				o();
			}
		});
		queue.length = 0;
	};

	/**
	 * 随机数
	 */
	var _random = function(){
		return parseInt(100000*Math.random());
	};

	/**
	 * 打开遮罩
	 */
	var _mask_open = function(f){
		
		var _mid = _random();
		var _mask = $("<div>").addClass(!f?"vjs-view-mask":"vjs-view-mask2").attr("id", _mid);
		$("body").append(_mask);
		if(f){
			var loading = $("<i>").addClass("iconfont icon-loading vjs-layer-loading");
			$("body").append(loading);
		}
		return _mid;
	};

	/**
	 * 关闭遮罩
	 */
	var _mask_close = function(mid){
		$("#"+mid).remove();
		$(".vjs-layer-loading").remove();
	};

	/**
	 * 渲染模板，补充{{each 1...4}}循环方法
	 */
	var _render = function(t, config){
		if(!t||!t.html())
			return false;
		var arr = t.html().match(/\{\{each(.+?)+\.\.\.+(.+?)\}\}/g);
		if(arr&&arr.length>0){
			$.each(arr, function(i,o){
				var param = o.replace("{{each","").replace("}}","");
				var start = param.trim().split("...")[0];
				var end = param.trim().split("...")[1];
				try{var obj = eval(start); start = obj;}catch(err){}
				try{var obj = eval(end); end = obj;}catch(err){}
				if(!isNaN(start)){
					start = Number(start);
				}
				else{
					var p = start.split(".");
					if(p.length==1){
						start = config.data[p[0]];
					}
					else if(p.length==2){
						start = config.data[p[0]][p[1]];
					}
					else if(p.length==3){
						start = config.data[p[0]][p[1]][p[2]];
					}
					else if(p.length==4){
						start = config.data[p[0]][p[1]][p[2]][p[3]];
					}
				}
				if(!isNaN(end)){
					end = Number(end);
				}
				else{
					var p = end.split(".");
					if(p.length==1){
						end = config.data[p[0]];
					}
					else if(p.length==2){
						end = config.data[p[0]][p[1]];
					}
					else if(p.length==3){
						end = config.data[p[0]][p[1]][p[2]];
					}
					else if(p.length==4){
						end = config.data[p[0]][p[1]][p[2]][p[3]];
					}
				}
				var list = [];
				if(start<=end){
					for(var j=start; j<end;j++){
						list.push(j);
					}
				}
				else{
					for(var j=start; j>end;j--){
						list.push(j);
					}
				}
				var name = "d"+parseInt(100000*Math.random());
				config.data[name] = list;
				var tem = "{{each "+name+" as $sort}}";
				t.html(t.html().replace(o, tem));
			});
		}
	};

	/**
	 * 设置表头
	 */
	var _setHeader = function(request){
		var okey = $.cookie("okey");
		if(okey){
			var encrypt = new JSEncrypt();
			encrypt.setPublicKey(okey);
			var timestamp = Date.parse(new Date()); 
			var token = encrypt.encrypt(timestamp);
			request.setRequestHeader("token", token);
		}
		return request;
	};

	return{
		
		/**
		 * 配置参数
		 */
		cong: function(config){
			if(config){
				$.each(config, function(i,o){
					$.cookie(i,o);
				});
			}
		},
		
		/**
		 * 加载模板
		 * 参数：
		 * container:容器；
		 * template:模板；
		 * alias:别名；
		 * succeed:成功回调函数，建议_load与succeed尽量不要同时使用
		 */
		template:function(config){
			if(!config){
				console.log("缺少参数配置...");
				return false;
			}
			var container;
			if(typeof(config.container)=="object"){
				container = config.container;
			}
			else{
				container = $(config.container);
			}
			var t = null;
			try{
				t = $("script[id='"+config.template+"']");
			}
			catch(error){}
			if(!t || t.length == 0){
				container.load(config.template, function(response, status, xhr) {
					var temp = config.alias?config.alias:config.template;
					if(!config.alias){
						if(temp.lastIndexOf(".")>0){
							temp = temp.substr(0,temp.lastIndexOf("."));
						}
						if(temp.lastIndexOf("/")>=0){
							temp = temp.substr(temp.lastIndexOf("/")+1);
						}
					}
					var tt = $("script[id='"+temp+"']");
					_render(tt, config);
					var html = template(temp, config.data);
					container.append(html);
					$("script[id='"+temp+"']").remove();
					_load();
					if(config.succeed){
						config.succeed();
					}
				});
			}
			else{
				_render(t, config);
				var html = template(config.template, config.data);
				container.append(html);
				_load();
				if(config.succeed){
					config.succeed();
				}
			}
		},

		/**
		 * 标签形式加载模板
		 */
		templated:function(){
			var temps = $("[data-template]");
			$.each(temps ,function(i,o){
				var temp = $(o).attr("data-template");
				var set = $(o).attr("data-object");
				var url = $(o).attr("data-url");
				var alias = $(o).attr("template-alias");
				if(url){
					vjs.ajax({//分装的ajax请求
						url:$(o).attr("data-url"),
						type:!$(o).attr("data-method")?"get":$(o).attr("data-method"),
						dataType:!$(o).attr("data-type")?"json":$(o).attr("data-type"),
						data:!$(o).attr("data-params")?{}:eval("("+$(o).attr("data-params")+")"),
						async:$(o).attr("data-async")==undefined?true:($(o).attr("data-params")=="true"?true:false),
						success:function(result){
							vjs.template({
								container:$(o),
								template:temp,
								data:result,
								alias:alias?alias:""
							});
						}
					});
				}
				else{
					var config = {
						container:$(o),
						template:temp,
						data:set?eval(set):{},
						alias:alias?alias:""
					};
					vjs.template(config);
				}
			});
		},

		/**
		 * 添加待处理事件
		 */
		load:function(events){
			if(events){
				_func.push(events);
			}
		},

		/**
		 * 添加window.load事件
		 */
		wload:function(events){
			var _funs = window.onload;
			if(typeof window.onload!='function'){ 
				if(events){
					window.onload=events; 
				}
			}else{ 
				window.onload=function(){ 
					_funs(); 
					if(events){
						events();
					}
				};
			} 
		},

		/**
		 * alert
		 */
		alerts:function(config){
			if(!config){
				console.log("缺少参数配置...");
				return false;
			}
			var _mid = _mask_open();
			var template = config.template?config.template:(js_document+"/alert.html");
			var _alert_id = "vjs_alert_"+_random();
			var container = $("<div>").addClass("vjs-view-alert col-xs-8 col-sm-4 col-md-2 col-xs-offset-2 col-sm-offset-1 col-md-offset-1").attr("id",_alert_id);
			vjs.template({
				container: container,
				template: template,
				data:{
					alert_id:container.attr("id"),
					title:config.title?config.title:"提示",
					content:config.content?config.content:"",
					btn:config.btn?config.btn:"确定",
				}
			});
			$("body").on("click", ".vjs-view-alert-title>i.icon-shibai[data-id='"+_alert_id+"']", function(){
				$("#"+container.attr("id")).remove();
				_mask_close(_mid);
				if(config.close){
					config.close();
				}
			});

			$("body").on("click", ".vjs-view-alert-footer>.vjs-alert-btn[data-id='"+_alert_id+"']", function(){
				$("#"+container.attr("id")).remove();
				_mask_close(_mid);
				if(config.close){
					config.close();
				}
			});
			$("body").append(container);
		},

		alert:function(content, callback){
			vjs.alerts({
				title: "提示",
				content: content,
				close: callback
			});
		},

		/**
		 * confirm
		 */
		confirms:function(config){
			if(!config){
				console.log("缺少参数配置...");
				return false;
			}
			var _mid = _mask_open();
			var template = config.template?config.template:(js_document+"/confirm.html");
			var _confirm_id = "vjs_confirm_"+_random();
			var container = $("<div>").addClass("vjs-view-confirm col-xs-8 col-sm-4 col-md-2 col-xs-offset-2 col-sm-offset-1 col-md-offset-1").attr("id",_confirm_id);
			vjs.template({
				container: container,
				template: template,
				data:{
					confirm_id:container.attr("id"),
					title:config.title?config.title:"确认",
					content:config.content?config.content:"",
					centain_btn:config.btn?config.btn:"确定",
					cancel_btn:config.btn?config.btn:"取消",
				}
			});
			$("body").on("click", ".vjs-view-confirm-title>i.icon-shibai[data-id='"+_confirm_id+"']", function(){
				$("#"+container.attr("id")).remove();
				_mask_close(_mid);
				if(config.cancel){
					config.cancel();
				}
			});

			$("body").on("click", ".vjs-view-confirm-footer>.vjs-confirm-cancel-btn[data-id='"+_confirm_id+"']", function(){
				$("#"+container.attr("id")).remove();
				_mask_close(_mid);
				if(config.cancel){
					config.cancel();
				}
			});

			$("body").on("click", ".vjs-view-confirm-footer>.vjs-confirm-centain-btn[data-id='"+_confirm_id+"']", function(){
				$("#"+container.attr("id")).remove();
				_mask_close(_mid);
				if(config.centain){
					config.centain();
				}
			});
			$("body").append(container);
		},

		confirm:function(content, centainback, cancelback){
			vjs.confirms({
				content: content,
				centain:centainback,
				cancel:cancelback
			});
		},

		/**
		 * dialog
		 */
		dialog:function(title, config){
			if(!config){
				console.log("缺少参数配置...");
				return false;
			}
			var _mid = _mask_open();
			var _dialog_id = "vjs_dialog_"+_random();
			var _container = $("<div>").addClass("vjs-view-dialog col-xs-12 col-sm-6 col-md-4").attr("id",_dialog_id);
			var _dialog = $("<div>").addClass("vjs-view-dialog-body");
			var _title = $("<div>").addClass("vjs-view-dialog-title").text(title?title:"新窗体");
			var _close = $("<i>").addClass("iconfont icon-shibai").css("float","right");
			var _content = $("<div>").addClass("vjs-view-dialog-content");
			_container.append(_dialog).append(_content);
			_dialog.append(_title);
			_title.append(_close);
			config.container = _content;
			vjs.template(config);
			_close.on("click", function(){
				_container.remove();
				_mask_close(_mid);
				if(config.close){
					config.close();
				}
			});
			$("body").append(_container);
		},

		/**
		 * ajax请求
		 */
		ajax:function(config){
			if(!config || !config.url){
				vjs.alert({
					content:"缺少url参数"
				});
				return false;
			}
			if(!config.type){
				config.type="post";
			}
			if(!config.dataType){
				config.dataType = "json";
			}
			if(config.async==undefined){
				config.async = true;
			}
			var _mask_id = null;
			$.ajax({
				url:config.url,
				type:config.type,
				data:config.data?config.data:{},
				dataType:config.dataType,
				async:config.async,
				beforeSend: function(request) {
					request = _setHeader(request);
//					if(!config.async){
//						_mask_id = _mask_open();
//					}
					_mask_id = _mask_open(true);
				},
				success:function(data){
//					if(!config.async){
//						_mask_close(_mask_id);
//					}
					_mask_close(_mask_id);
					if(config.success){
						config.success(data);
					}
				},
				error: function(XMLHttpRequest, textStatus, errorThrown){
//					if(!config.async){
//						_mask_close(_mask_id);
//					}
					_mask_close(_mask_id);
					if(config.error){
						config.error(XMLHttpRequest, textStatus, errorThrown);
					}
				}
			});
		},

		/**
		 * 获取URL参数
		 */
		getUriParam: function(url, name){
			if(url.indexOf("?")>0){
				url = url.substr(url.indexOf("?")+1);
				var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
				var r = url.match(reg);
				if(r!=null)return  decodeURI(r[2]); return null;
			}
			else{
				return null;
			}
		},

		/**
		 * RSA加密
		 */
		REncrypt: function(pkey, content) {
			if(!pkey){
				vjs.alert("缺少公钥...");
				return false;
			}
			var encrypt = new JSEncrypt();
			encrypt.setPublicKey(pkey);
			var encrypted = encrypt.encrypt(content);
			return encrypted;
		},

		/**
		 * json格式转换
		 */
		Json:function(){//json格式转化
			return{
				toString:function(obj){
					return JSON.stringify(obj);
				},
				parse:function(json){
					return eval("("+json+")");
				}
			};
		},

		/**
		 * websocket
		 */
		ws:function(config){
			var websocket = null;
			//判断当前浏览器是否支持WebSocket
			if ('WebSocket' in window) {
				websocket = new WebSocket("ws://localhost:8080/webSocketServer?user=weizx");
			} else {
				vjs.alert('当前浏览器 Not support websocket');
			}
			//连接发生错误的回调方法
			websocket.onerror = function() {
				if(config.errorback){
					config.errorback();
				}
			};
			//连接成功建立的回调方法
			websocket.onopen = function() {
				if(config.openback){
					config.openback();
				}
			};
			//接收到消息的回调方法
			websocket.onmessage = function(event) {
				if(config.msgback){
					config.msgback(event.data);
				}
			};
			//连接关闭的回调方法
			websocket.onclose = function() {
				if(config.colseback){
					config.colseback();
				}
			};
			//监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
			window.onbeforeunload = function() {
				websocket.close();
			};
			return {
				send:function(receiver, content, isgroup){
					var msg = new Object();
					msg.receiver = receiver;
					msg.content = content;
					msg.isgroup = isgroup;
					websocket.send(vjs.json().toString(msg));
				}
			};
		},

		/**
		 * 定位服务
		 */
		position:function(){
			return{
				fixed:function(callback){//定位，获取当前的经纬度
					//获取定位信息
					var map,geolocation;
					map = new AMap.Map('container', {
						resizeEnable: true
					});
					map.plugin('AMap.Geolocation', function() {
						geolocation = new AMap.Geolocation({
							enableHighAccuracy: true,//是否使用高精度定位，默认:true
							timeout: 10000,          //超过10秒后停止定位，默认：无穷大
							buttonOffset: new AMap.Pixel(10, 20),//定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
							zoomToAccuracy: true,      //定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
							buttonPosition:'RB'
						});
						geolocation.getCurrentPosition();
						AMap.event.addListener(geolocation, 'complete', function(data){
							if(callback){
								var poi = new Object();
								poi.x = data.position.getLng();
								poi.y = data.position.getLat();
								poi.code = data.addressComponent.citycode;
								callback(poi);
							}
						});
						AMap.event.addListener(geolocation, 'error', function(data){
							if(callback){
								var poi = new Object();
								poi.x = null;
								poi.y = null;
								poi.code = "";
								callback(poi);
							}
						}); 
					});
				},
				marker:function(container, poi, callback){//标点，含点击事件
					if(!poi||!poi.x||!poi.y){
						return;
					}
					var map = new AMap.Map(container, {
						resizeEnable : true,
						zoom : 20
					});
					map.clearMap();
					new AMap.Marker({ //加点
						map : map,
						position : [poi.x, poi.y]
					});
					map.setFitView();
					map.on("click", function(e){
						map.clearMap();
						new AMap.Marker({ //加点
							map : map,
							position : [e.lnglat.getLng(), e.lnglat.getLat()]
						});
						map.setFitView();
						if(callback){
							poi.x = e.lnglat.getLng();
							poi.y = e.lnglat.getLat();
							callback(poi);
						}
					});
				},
				lnglat:function(code, search, callback){//搜索地区返回经纬度
					var geocoder = new AMap.Geocoder({
						city: !code?"":code, //城市，默认：“全国”
								radius: 10000 //范围，默认：500
					});
					geocoder.getLocation(search, function(status, result) {
						if (status === 'complete' && result.info === 'OK') {
							if(callback){
								if (result.geocodes.length > 0) {
									var position = result.geocodes[0];
									var poi = new Object();
									poi.x = position.location.lng;
									poi.y = position.location.lat;
									poi.code = position.addressComponent.citycode;
									callback(poi);
								}
								else{
									var poi = new Object();
									poi.x = null;
									poi.y = null;
									poi.cdoe = "";
									callback(poi);
								}
							}
						}
						else{
							if(callback){
								var poi = new Object();
								poi.x = null;
								poi.y = null;
								poi.cdoe = "";
								callback(poi);
							}
						}
					});
				},
				address:function(poi, callback){//根据经纬返回地理信息
					var geocoder = new AMap.Geocoder({
						radius: 1000,
						extensions: "all"
					});
					geocoder.getAddress([poi.x, poi.y], function(status, result) {
						if (status === 'complete' && result.info === 'OK') {
							if(callback){
								poi.code = result.regeocode.addressComponent.citycode;
								callback(poi, result.regeocode.formattedAddress);
							}
						}
					});
				},
				convert:function(address){//解析地址获取详细地址
					if(address.indexOf("街道")>0){
						address = address.substring(address.indexOf("街道")+2);
					}
					else if(address.indexOf("区")>0){
						address = address.substring(address.indexOf("区")+1);
					}
					else if(address.indexOf("市")>0){
						address = address.substring(address.indexOf("市")+1);
					}
					return address;
				},
				parse:function(address){//解析地址获取
					if(address.indexOf("街道")>0){
						address = address.substring(0, address.indexOf("街道")+2);
					}
					else if(address.indexOf("区")>0){
						address = address.substring(0, address.indexOf("区")+1);
					}
					else if(address.indexOf("市")>0){
						address = address.substring(0, address.indexOf("市")+1);
					}
					return address;
				}
			};
		},

		/**
		 * 页面路由
		 */
		view: function(){
			return {
				to:function(url, target){
					var _route = $.cookie("route");
					var list = new Array();
					if(_route){
						list = vjs.Json().parse(_route);
					}
					var local = window.location.href;
					var _target = vjs.getUriParam(local, "target");
					if(!_target){
						list.push(local);
					}
					_route = vjs.Json().toString(list);
					$.cookie("route", _route);
					if(target){
						if(url.indexOf("?")>0){
							if(url.indexOf("&")>0){
								url = new String(url+"&target="+target);
							}
							else{
								url = new String(url+"target="+target);
							}
						}
						else{
							url = new String(url+"?target="+target);
						}
					}
					window.location.href = url;
				},
				back:function(){		
					var _target = vjs.getUriParam(window.location.href, "target");
					if(!_target){
						var _route = $.cookie("route");
						if(!_route){
							window.history.back();
						}
						else{
							var list = vjs.Json().parse(_route);
							var url = list.pop();
							_route = vjs.Json().toString(list);
							$.cookie("route", _route);
							window.location.href = url;
						}
					}
					else{
						vjs.view().to(_target);
					}
				}
			};
		}
	};
}();


vjs.wload(function(){
	//加载并渲染模板
	vjs.templated();
	//关闭遮罩
//	setTimeout(function(){
//		if(document.getElementById("vjs-view-loading")){
//			document.getElementById("vjs-view-loading").remove();
//		}
//	},300);
});